package com.atguigu.gulimall.product.service.impl;

import org.aspectj.bridge.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryList = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = categoryList.stream()
                .filter(c -> c.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildList(menu, categoryList));
                    return menu;
                }).sorted((x1, x2) -> {
                    return x1.getSort() == null ? 0 : x2.getSort() == null ? 0 : x1.getSort() - x2.getSort();
                }).collect(Collectors.toList());

        return level1Menus;
    }

    List<CategoryEntity> getChildList(CategoryEntity menu, List<CategoryEntity> categoryAll) {
        List<CategoryEntity> childList = categoryAll.stream()
                .filter(s -> s.getParentCid() == menu.getCatId())
                .sorted((x1, x2) -> {
                    return x1.getSort() == null ? 0 : x2.getSort() == null ? 0 : x1.getSort() - x2.getSort();
                }).map(s -> {
                    s.setChildren(getChildList(s, categoryAll));
                    return s;
                }).collect(Collectors.toList());
        return childList;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

}